//
//  NEDInputTextField.m
//  AddressBookCloud
//
//  Created by 林宁宁 on 2020/5/10.
//  Copyright © 2020 林宁宁. All rights reserved.
//

#import "NEDInputTextField.h"
#import "UIView+NEDInputAccessory.h"
#import "UIColor+NEDStyle.h"
#import "UIFont+NED.h"
#import "NEDDefines.h"
#import "NSMutableAttributedString+NED.h"
#import "NEDConstant.h"
#import "UIView+NED.h"
#import "NSDecimalNumber+NED.h"

@interface NEDInputTextField()<UITextFieldDelegate>

@property(nonatomic, strong) UIButton *verificationCodeButton;

@end

@implementation NEDInputTextField

-(instancetype)init{
    self = [super init];
    if(self){
        self.backgroundColor = [UIColor ned_background];
        self.textColor = [UIColor ned_h1];
        self.textAlignment = NSTextAlignmentLeft;
        self.font = [UIFont ned_pfOfSize:16];
        self.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.delegate = self;
        [self addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        WS(weakSelf);
        [self showAccessoryDown:^{
            [weakSelf resignFirstResponder];
        }];
    }
    return self;
}

-(void)setFormat:(id<NEDInputFormatProtocol>)format{
    _format = format;
    if([format respondsToSelector:@selector(formatKeyBoardType)]){
        self.keyboardType = [format formatKeyBoardType];
    }
}

-(void)setNed_placeholder:(NSString *)ned_placeholder{
    _ned_placeholder = ned_placeholder;
    
    self.attributedPlaceholder = [NSMutableAttributedString ned_initWithStr:ned_placeholder customBlock:^(NSMutableAttributedString *att) {
        [att ned_font:[UIFont ned_pflOfSize:14]];
        [att ned_color:[UIColor ned_placeholder]];
    }];
}
- (void)addLeftViewShowWidth:(CGFloat)width image:(UIImage *)image imgSize:(CGSize)imgSize withImageViewConfig:(void (^)(UIImageView *imageView))blockImageView{
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imgSize.width, imgSize.height)];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.image = image;
    if (blockImageView) {
        blockImageView(imageView);
    }
    [self addHeadViewShowWidth:width customView:imageView isLeft:YES];
}

- (void)addLeftViewShowWidth:(CGFloat)width image:(UIImage *)image imgSize:(CGSize)imgSize{
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imgSize.width, imgSize.height)];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.image = image;
    [self addHeadViewShowWidth:width customView:imageView isLeft:YES];
}
- (void)addRightViewShowWidth:(CGFloat)width image:(UIImage *)image imgSize:(CGSize)imgSize withAddClick:(void (^)(void))block{
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imgSize.width, imgSize.height)];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.image = image;
 
    [imageView addTapClick:block];
 
    [self addHeadViewShowWidth:width customView:imageView isLeft:NO];
}

- (void)addRightViewShowWidth:(CGFloat)width image:(UIImage *)image imgSize:(CGSize)imgSize{
    [self addRightViewShowWidth:width image:image imgSize:imgSize withAddClick:nil];
}
- (void)addLeftViewShowWidth:(CGFloat)width title:(NSString *)title withFont:(CGFloat)font{
    [self addHeadViewShowWidth:width attributeTitle:[NSMutableAttributedString ned_initWithStr:title customBlock:^(NSMutableAttributedString *att) {
        [att ned_font:[UIFont ned_pflOfSize:font]];
        [att ned_color:[UIColor ned_h1]];
    }] isLeft:YES];
}
- (void)addLeftViewShowWidth:(CGFloat)width title:(NSString *)title{
    [self addLeftViewShowWidth:width title:title withFont:16];
}
- (void)addRightViewShowWidth:(CGFloat)width title:(NSString *)title{
    [self addHeadViewShowWidth:width attributeTitle:[NSMutableAttributedString ned_initWithStr:title customBlock:^(NSMutableAttributedString *att) {
        [att ned_font:[UIFont ned_pflOfSize:16]];
        [att ned_color:[UIColor ned_h1]];
    }] isLeft:NO];
}

- (void)addViewShowWidth:(CGFloat)width title:(NSString *)title image:(UIImage *)image left:(BOOL)isLeft{
    
    NSMutableAttributedString * attribute = [NSMutableAttributedString new];
    [attribute ned_attachImage:[[UIColor clearColor] ned_drawImageWithColor] imageSize:CGSizeMake(Adapted(6), Adapted(8))];
    [attribute ned_attachImage:image imageSize:CGSizeMake(25, 25)];
    [attribute ned_attachImage:[[UIColor clearColor] ned_drawImageWithColor] imageSize:CGSizeMake(Adapted(8), Adapted(8))];
    [attribute ned_appendStr:title block:^(NSMutableAttributedString *attStr, NSString *str) {
        [attStr ned_font:[UIFont ned_pfOfSize:16]];
        [attStr ned_color:[UIColor ned_h1]];
    }];
    [attribute ned_baseLineOffset:(25-16)*0.5 range:[attribute.string rangeOfString:title]];
    
    [self addHeadViewShowWidth:width attributeTitle:attribute isLeft:isLeft];
}

- (void)addHeadViewShowWidth:(CGFloat)width attributeTitle:(NSAttributedString *)attribute isLeft:(BOOL)isLeft{
    UILabel * titleView = [UILabel new];
    titleView.textAlignment = NSTextAlignmentCenter;
    titleView.numberOfLines = 0;
    titleView.attributedText = attribute;
    
    [self addHeadViewShowWidth:width customView:titleView isLeft:isLeft];
}



- (void)addHeadViewShowWidth:(CGFloat)width customView:(UIView *)customView isLeft:(BOOL)isLeft{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIView * contentView = nil;
        if(isLeft){
            [self cleanLeftView];
            self.leftContentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, CGRectGetHeight(self.frame))];
            contentView = self.leftContentView;
            self.leftView = contentView;
            self.leftViewMode = UITextFieldViewModeAlways;
        }else{
            [self cleanRightView];
            self.rightContentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, CGRectGetHeight(self.frame))];
            contentView = self.rightContentView;
            self.rightView = contentView;
            self.rightViewMode = UITextFieldViewModeAlways;
        }
        if(customView){
            [contentView addSubview:customView];
            if(CGRectIsEmpty(customView.frame)){
                [customView sizeToFit];
            }
            customView.center = contentView.center;
                       
            if(isLeft){
                self.leftView = contentView;
                self.leftViewMode = UITextFieldViewModeAlways;
            }else{
                self.rightView = contentView;
                self.rightViewMode = UITextFieldViewModeAlways;
            }
            
        }else{
            if(isLeft){
                [self cleanLeftView];
            }
            else{
                [self cleanRightView];
            }
        }
    });

}




- (void)cleanLeftView{
    self.leftContentView = nil;
    self.leftView = nil;
}
- (void)cleanRightView{
    self.rightContentView = nil;
    self.rightView = nil;
}


#pragma mark - textfield

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    BOOL canInputSpace = NO;
    if(self.format && [self.format respondsToSelector:@selector(formatAllowInputSpace)]){
        canInputSpace = [self.format formatAllowInputSpace];
    }
    if(!canInputSpace){
        //屏蔽空格
    NSString * tem = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsJoinedByString:@""];
        if (![string isEqualToString:tem]) {
            // 如果是输入法中选择的话没法走这个回调，但是会返回一个空格，在这里手动调用
            [self textFieldDidChange:textField];
            return NO;
        }
    }
    //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
    if (string.length == 0) {
        return YES;
    }
    /// 是否使用正则校验
    NSString * regex = nil;
    if(self.format && [self.format respondsToSelector:@selector(formatMatchRegexInputing)]){
        regex = [self.format formatMatchRegexInputing];
    }
    if(regex){
        NSString * checkStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
        return [predicate evaluateWithObject:checkStr];
    }
    
    /// 输入字符检验
    NSString * limitString = nil;
    if(self.format && [self.format respondsToSelector:@selector(formatInputLimitChar)]){
        limitString = [self.format formatInputLimitChar];
    }

    if(IsNonNull(limitString)){
        NSCharacterSet * cs = [[NSCharacterSet characterSetWithCharactersInString:limitString] invertedSet];
        NSString * filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        if([string isEqualToString:filtered]){
            if([string isEqualToString:@"."] && [textField.text containsString:@"."]){
                return NO;
            }
            return YES;
        }else{
            return NO;
        }
    }
    
    return YES;
}

-(void)textFieldDidChange:(UITextField *)textField{
    
    /** 限制输入字数 */
    NSInteger maxAmount = 0;
    if(self.format && [self.format respondsToSelector:@selector(formatMaxTextLength)]){
        maxAmount = [self.format formatMaxTextLength];
    }
    
    /// 限定需要输入字符数量 有设定最大输入的个数也为这个数
    NSInteger limitCount = 0;
    if(self.format && [self.format respondsToSelector:@selector(formatLimitLength)]){
        limitCount = [self.format formatLimitLength];
        if(limitCount > 0){
            maxAmount = limitCount;
        }
    }
    
    if(maxAmount > 0){
        NSString * toBeString = textField.text;
        //获取高亮部分
        UITextRange * selectedRange = [textField markedTextRange];
        UITextPosition * position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position)
        {
            if (toBeString.length > maxAmount)
            {
                NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxAmount];
                if (rangeIndex.length == 1)
                {
                    textField.text = [toBeString substringToIndex:maxAmount];
                }
                else
                {
                    NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxAmount)];
                    textField.text = [toBeString substringWithRange:rangeRange];
                }
            }
        }
    }
    
    // 小数位数
    if(self.format && [self.format respondsToSelector:@selector(formatDecimalLength)]){
        NSInteger decimal = [self.format formatDecimalLength];
        
        NSArray * values = [textField.text componentsSeparatedByString:@"."];
        if(values.count > 1){
            NSString * deciStr = values.lastObject;
            if(deciStr.length > decimal){
                textField.text = textField.text.ned_decimalDown(decimal);
            }
        }
    }
    
    if(self.didChangeBlock){
        self.didChangeBlock(self);
    }
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    return !self.canPerform;
}



- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason{
    if (self.endEditBlock) {
        self.endEditBlock(self);
    }
}


-(BOOL)unUsable{
    if(self.format && [self.format respondsToSelector:@selector(formatLimitLength)]){
        NSInteger limitCount = [self.format formatLimitLength];
        if(limitCount > 0){
            if(self.text.length != limitCount){
                return YES;
            }
        }
    }
    
    NSString * regex = nil;
    if(self.format && [self.format respondsToSelector:@selector(formatMatchRegexDone)]){
        regex = [self.format formatMatchRegexDone];
    }
    if(regex){
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
        if(![predicate evaluateWithObject:self.text]){
            //如果不匹配 内容无效
            return YES;
        }
    }
    
    //是空的
    if(IsNull(self.text)){
        return YES;
    }
    
    return NO;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if(self.beginEditBlock){
        return self.beginEditBlock(self);
    }
    return YES;
}

@end
